package com.etc.service.impl;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.etc.dao.GoodsMapper;
import com.etc.entity.Goods;
import com.etc.entity.GoodsExample;
import com.etc.service.GoodsService;
import com.etc.tools.AjaxOperateResponse;
import com.etc.tools.ResponseData;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

@Service
public class GoodsServiceImpl implements GoodsService {

	@Autowired
	private GoodsMapper goodsMapper;

	@Override
	public ResponseData<Goods> getGoodsByLike(String keywords, Date begindate, Date enddate, Integer page,
			Integer limit) {
		PageHelper.startPage(page, limit);
		GoodsExample example = new GoodsExample();
		if(begindate == null && enddate == null) {
			example.createCriteria().andGoodsnameLike("%" + keywords + "%");
		}
		else if(begindate != null && enddate == null)
		{
			example.createCriteria().andGoodsnameLike("%" + keywords + "%").andPubdateGreaterThanOrEqualTo(begindate);
		}else if(begindate == null && enddate != null){
			example.createCriteria().andGoodsnameLike("%" + keywords + "%").andPubdateLessThanOrEqualTo(enddate);
		}else {
			example.createCriteria().andGoodsnameLike("%" + keywords + "%").andPubdateBetween(begindate, enddate);
		}
		
		//orderdate <=DATE_ADD(?,INTERVAL 1 DAY))
		

		List<Goods> list = goodsMapper.selectByExample(example);
		PageInfo pageInfo = new PageInfo(list);
		ResponseData<Goods> rd = new ResponseData<Goods>(0, "success", pageInfo.getTotal(), list);
		return rd;
	}

	@Override
	public AjaxOperateResponse addGoods(Goods goods) {
		int result = goodsMapper.insertSelective(goods);
		// 固定操作失败
		AjaxOperateResponse<Goods> rd = new AjaxOperateResponse<Goods>(0, "error");
		if (result > 0) {
			rd.setCode(200);
			rd.setMsg("success");
		}

		return rd;

	}

	@Override
	public AjaxOperateResponse updateGoods(Goods goods) {
		int result = goodsMapper.updateByPrimaryKeySelective(goods);
		// 固定操作失败
		AjaxOperateResponse<Goods> rd = new AjaxOperateResponse<Goods>(0, "error");
		if (result > 0) {
			rd.setCode(200);
			rd.setMsg("success");
		}

		return rd;
	}

	@Override
	public AjaxOperateResponse delGoods(Integer goodsid) {
		int result = goodsMapper.deleteByPrimaryKey(goodsid);
		// 固定操作失败
		AjaxOperateResponse<Goods> rd = new AjaxOperateResponse<Goods>(0, "error");
		if (result > 0) {
			rd.setCode(200);
			rd.setMsg("success");
		}

		return rd;
	}

	@Override
	public Goods getGoodsById(Integer goodsid) {
		// TODO Auto-generated method stub
		return goodsMapper.selectByPrimaryKey(goodsid);
	}

}
